//
//  DeviceControlController.m
//  YSSmartHome
//
//  Created by Yahaong on 16/8/12.
//  Copyright © 2016年 yahaong. All rights reserved.
//

#import "DeviceControlController.h"
#import "ZTControlMessageCell.h"
#import "ZTControlTopView.h"
#import "OperationModel.h"

@interface DeviceControlController ()
<
DataManagerRefreshDelegate,
UITableViewDelegate,
UITableViewDataSource
>
@property(nonatomic, strong)UITableView *tableView;
//@property (nullable, nonatomic, strong) UINavigationBar* navigationBar;
//@property (nullable, nonatomic, strong) UINavigationItem *titleItem;
@property(nonatomic, strong)ZTControlTopView *topView;
@end

@implementation DeviceControlController


#pragma mark - life cycle
- (void)dealloc
{
    [kDataManager removeRefreshDelegate:self];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initSubviews];
    [kDataManager addRefreshDelegate:self];
    [self setData];
}
- (void)initSubviews
{
    [self setupTopView:self.device];
    [self.view addSubview:self.tableView];
    [self setConstraint];
}
- (void)setConstraint
{
    __weak typeof(self)weakSekf = self;
    [self.topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.trailing.leading.equalTo(self.view).offset(UIEdgeInsetsMake(64, 0, 0, 0));
        if (weakSekf.device.devType  == ZTDeviceTypeThreeWaySwitch
                 || weakSekf.device.devType  == ZTDeviceTypeThreeWay0Switch
                 || weakSekf.device.devType  == ZTDeviceTypeFourWaySwitch
                 || weakSekf.device.devType  == ZTDeviceTypeFourWay0Switch)
        {
            make.height.equalTo(kIphoneSize_Height(300));
        }
        else
        {
            make.height.equalTo(kIphoneSize_Height(250));
        }
    }];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.bottom.equalTo(self.view);
        make.top.equalTo(self.topView.bottom);
    }];
}

#pragma mark - event response

- (void)backPreviousVC {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setData
{
    NSString *strName = [self.device getDeviceName];
    self.titleItem.title = strName;
    switch (self.device.devType) {
        case ZTDeviceTypeOneWay0Switch:
        case ZTDeviceTypeOneWaySwitch:
        case ZTDeviceTypeZTDoorsensor:
        case ZTDeviceTypeInfraredDetector:
        case ZTDeviceTypeOneWaySocket:
        case ZTDeviceTypeSmoke:
        case ZTDeviceTypeAir:
        case ZTDeviceTypeGAS:
        case ZTDeviceTypeFlooding:
        case ZTDeviceTypeAlarmkey:
        case ZTDeviceTypeCurtainSingleTrack:
        {
            ZTOneControlDevice *device = (ZTOneControlDevice *)self.device;
            [self.topView setChannel:1 status:device.status];
        }
            break;
        case ZTDeviceTypeTwoWay0Switch:
        case ZTDeviceTypeTwoWaySwitch:
        case ZTDeviceTypeTwoWaySocket:
        case ZTDeviceTypeCurtainDoubleTrack:
        {
            [self setTwoWaySwitchData];
        }
            break;
        case ZTDeviceTypeThreeWay0Switch:
        case ZTDeviceTypeThreeWaySwitch:
        case ZTDeviceTypeThreeWaySocket:
        {
            [self setThreeWaySwitchData];
        }
            break;
        case ZTDeviceTypeFourWay0Switch:
        case ZTDeviceTypeFourWaySwitch:
        case ZTDeviceTypeFourWaySocket:
        {
            [self setFourWaySwitchData];
        }
            break;
        default:
            break;
    }
}
- (void)setDevice:(ZTDevice *)device
{
    _device = device;
}
- (void)setTwoWaySwitchData
{
    ZTTwoControlDevice *device = (ZTTwoControlDevice *)self.device;
    [self.topView setChannel:1 status:device.oneStatus];
    [self.topView setChannel:2 status:device.twoStatus];
    
}
- (void)setThreeWaySwitchData
{
    ZTThreeControlDevice *device = (ZTThreeControlDevice *)self.device;
    [self.topView setChannel:1 status:device.oneStatus];
    [self.topView setChannel:2 status:device.twoStatus];
    [self.topView setChannel:3 status:device.threeStatus];
}
- (void)setFourWaySwitchData
{
    ZTFourControlDevice *device = (ZTFourControlDevice *)self.device;
    [self.topView setChannel:1 status:device.oneStatus];
    [self.topView setChannel:2 status:device.twoStatus];
    [self.topView setChannel:3 status:device.threeStatus];
    [self.topView setChannel:4 status:device.fourStatus];
}

- (void)setupTopView:(ZTDevice* )dev
{
    ZTControlTopView *ctlTopView = [[ ZTControlTopView alloc]initWithDevType:dev.devType];
    self.topView = ctlTopView;
    [self.view addSubview:ctlTopView];
    if (![self.device isKindOfClass:[ZTNoControlDevice class]])
    {
        __weak typeof(self) wself = self;
        ctlTopView.block = ^(NSInteger index, BOOL status){
            __strong typeof(wself) sself= wself;
            if (!sself)
            {
                return;
            }
            [sself.device setCircuitStatus:!status which:index];
        };
    }
}

#pragma mark - UITableViewDataSource

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
    return self.device.operationGroups.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return  self.device.operationGroups[section].operations.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZTControlMessageCell *cell = [ZTControlMessageCell controlMessageCell:tableView];
    cell.operation = self.device.operationGroups[indexPath.section].operations[indexPath.row] ;
    if (self.device.operationGroups[indexPath.section].operations.count == 1)
    {
         cell.cellType = CellTypeNone;
    }
    else if (indexPath.row == 0)
    {
        cell.cellType = CellTypeTop;
    }
    else if (indexPath.row == self.device.operationGroups[indexPath.section].operations.count - 1 )
    {
        cell.cellType = CellTypeBottom;
    }
    else
    {
        cell.cellType = CellTypeMiddle;
    }
    return cell;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc]init];
    UILabel *label = [[UILabel alloc]init];
    [view addSubview:label];
    view.backgroundColor = [UIColor whiteColor];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(10);
        make.centerY.equalTo(view);
    }];

    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[self.device.operationGroups[section] time]];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/BeiJing"];
    [formatter setTimeZone: timeZone];
    [formatter setDateFormat:@"MM"];
    NSInteger currentMonth=[[formatter stringFromDate:date]integerValue];
    [formatter setDateFormat:@"dd"];
    NSInteger currentDay=[[formatter stringFromDate:date] integerValue];
    NSString *dateStr =  [NSString stringWithFormat:@"%zd",currentDay];
    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc]initWithString:dateStr attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:36]}] ;
    NSString *mouseStr =  [NSString stringWithFormat:@"%zd月",currentMonth];
    NSAttributedString *mouseAttriStr = [[NSAttributedString alloc]initWithString:mouseStr attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:13], NSForegroundColorAttributeName: RGBColor(163, 163, 163)}];
    [attributedStr appendAttributedString:mouseAttriStr];
 
    label.attributedText =  attributedStr;
    UILabel *weakLabel = [[UILabel alloc]init];
    weakLabel.textColor = RGBColor(163, 163, 163);
    weakLabel.font = [UIFont systemFontOfSize:13];
    [view addSubview:weakLabel];
    weakLabel.text = [self weekdayStringFromDate:date];
    [weakLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.equalTo(view.trailing).offset(-10);
        make.bottom.equalTo(label.bottom).offset(-5);
    }];
    return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 60;
}

#pragma mark - DataManagerRefreshDelegate

- (void)deviceRefresh:(DataManager *)manager callbackType:(DeviceCallbackType)callbackType
{
    switch (callbackType) {
        case DeviceCallbackTypeName:
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                self.navigationItem.title = [self.device getDeviceName];
            });
        }
            break;
        case DeviceCallbackTypeConnectStatus:
        case DeviceCallbackTypeStatus:
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self setData];
                [self.tableView reloadData];
            });
        }
            break;
        default:
            break;
    }
}

- (void)deviceHistoryOperationRefresh:(DataManager *)manager apsn:(XAITYPEAPSN)apsn luid:(XAITYPELUID)luid {
    if (self.device.apsn == apsn && self.device.luid == luid) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
    }
}
- (void)dataRefresh:(DataManager*)manager
{
//    dispatch_async(dispatch_get_main_queue(), ^{
        [self setData];
//        [self.tableView reloadData];
//    });
}


#pragma mark - private method 



#pragma mark - getters and setters

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.backgroundColor = [UIColor whiteColor];
    }
    return _tableView;
}

- (NSString *)weekdayStringFromDate:(NSDate *)inputDate {
    
    NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"星期天", @"星期一", @"星期二", @"星期三", @"星期四", @"星期五", @"星期六", nil];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/BeiJing"];
    [calendar setTimeZone: timeZone];
    NSCalendarUnit calendarUnit = NSCalendarUnitWeekday;
    NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:inputDate];
    return [weekdays objectAtIndex:theComponents.weekday];
}
@end
